<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="menu">
      <button data-action="save">Save</button>
      <button data-action="load">Load</button>
      <button data-action="search">Search</button>
      <button>abc</button>
    </div>
    <script>
      const methods = {
        save: function () {
          console.log(this);
          console.log("save");
        },
        load: function () {
          console.log(this);
          console.log("load");
        },
        search: function () {
          console.log(this);
          console.log("search");
        },
      };
      const menu = document.getElementById("menu");

      function on(el, type, methods, act = "action") {
        el.addEventListener(type, function (e) {
          const target = e.target;
          const action = target.dataset[act];
          //判断方法是否存在
          if (action === undefined || methods[action] === undefined) {
            return;
          }
          // call调用修改函数中this的值
          methods[action].call(target);
        });
      }
      on(menu, "click", methods, "action");
    </script>
  </body>
</html>
